<template>
  <div class="pay">
    <h1>点击去支付
      <span style="display: block" class="animate__animated animate__tada animate__infinite">⬇️</span>
    </h1>
    <button class="btn-content" @click="goPay">
      <div class="img-content">
        <img src="@/assets/img/wx_pay.png" alt="">
      </div>
      <h2>微信支付</h2>
    </button>
  </div>
</template>

<script>
import {goPay, createOrder, queryOrder, GetOrderList} from "../api";

export default {
  name: 'Pay',
  props: {
    ProductId: Number
  },
  computed: {
    _ProductId () {
      return this.ProductId
    }
  },
  data () {
    return {}
  },
  methods: {
    goPay () {
      // 判断获取订单列表是否有未支付订单，如果有，创建订单，提示首页去支付
      GetOrderList(1).then(res => {
        if (res) {
          // 创建订单
          createOrder(this._ProductId)
          this.Dialog({
            message: '您有未支付的订单,首页去支付'
          }).then(() => {
            this.$store.dispatch('changePayLayerState', false) // 关掉支付页面
            this.$router.go(0)
            location.reload()
          })
        } else {
          //  没有未支付订单，就直接跳转微信
          // 创建订单
          createOrder(this._ProductId).then(res => {
            sessionStorage.setItem('orderId', res.order_id) // 保存order_id
          })
          setTimeout(() => {
            const orderId = sessionStorage.getItem('orderId')
            // 支付
            goPay(orderId).then(res => {
              const wxUrl = res.mweb_url
              window.location.href = wxUrl
              //  查询订单是否支付成功
              this.QueryOrder(orderId)
            }).catch(err => {
              console.log(err)
            })
          }, 500)
        }
      })
    },
    QueryOrder (orderId) {
      // 查询是否支付成功
      queryOrder(orderId).then(res => {
        if (res) {
          this.Toast('支付成功')
        } else {
          this.Toast('支付失败')
        }
      })
    }
  },
  mounted () {
  }
}
</script>

<style lang="scss" scoped>
.pay {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  h1 {
    font-size: 20px;
    text-align: center;
    padding-bottom: 20px;
    display: flex;
  }

  .btn-content {
    display: flex;
    justify-content: center;
    align-items: center;
    border: none;
    outline: none;
    padding: 5px 8px;
    border-radius: 12px;

    h2 {
      font-size: 26px;
      text-align: center;
      padding: 15px 0;
      font-weight: 500;
    }

    img {
      width: 50px;
      margin-right: 8px;
    }
  }
}
</style>
